package com.kinpoway.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class TimeInterceptor implements HandlerInterceptor {

    // 控制器方法被调用之前执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        System.out.println("preHandle");
        // handler 是一个HandlerMethod；
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        httpServletRequest.setAttribute("startTime",new Date().getTime());
        return true;   //这个返回值决定是否会去执行控制器中的方法
    }


    //正常执行完调用，控制品方法抛出异常不会被执行
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");

    }

    // 不管方法是否正常执行都会执行
    // 当控制器方法抛出异常时，这里会接收到这个异常。
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");

    }
}
